package com.capgemini.simpleappblanche.services.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.capgemini.simpleappblanche.dao.ICustomerDao;
import com.capgemini.simpleappblanche.domain.customer.Customer;
import com.capgemini.simpleappblanche.dto.CustomerDto;
import com.capgemini.simpleappblanche.dto.SearchCustomerCriteria;
import com.capgemini.simpleappblanche.helper.CustomerHelper;
import com.capgemini.simpleappblanche.services.ICustomerService;
import com.capgemini.simpleappblanche.utils.AppMapper;

@Service
@Transactional
public class CustomerService implements ICustomerService {
	
	@Autowired
	private ICustomerDao customerDao;
  
    @Autowired
	private AppMapper mapperDozer;

	/**
	 * constructor
	 */
	public CustomerService() {
		super();
	}
	/**
	 * constructor
	 * @param customerDao customerDao
	 * @param mapperDozer mapperDozer
	 */
	public CustomerService(ICustomerDao customerDao, AppMapper mapperDozer) {
		super();
		this.customerDao = customerDao;
		this.mapperDozer = mapperDozer;
	}

	
	
	/**
	 * {@inheritDoc}
	 * @see com.capgemini.simpleappblanche.services.ICustomerService#findByCriteria(com.capgemini.simpleappblanche.dto.SearchCustomerCriteria, int)
	 */
	@Override
	public List<CustomerDto> findByCriteria(final SearchCustomerCriteria criteria,int nbElement) {
		
		//prepare search
		criteria.setName(CustomerHelper.getName(criteria.getName()));

		//search
		final List<Customer> result =  customerDao.findByCriteria(criteria,nbElement);
		
		return mapperDozer.mapList(result, CustomerDto.class);
	}

	/**
	 * {@inheritDoc}
	 * @see com.capgemini.simpleappblanche.services.ICustomerService#findById(long)
	 */
	@Override
	public CustomerDto findById(final long id) {
		final Customer result =  customerDao.findById(id);
		if(result != null){
			return mapperDozer.map(result, CustomerDto.class);
		}else{
			return null;
		}
	}
	
	/**
	 * {@inheritDoc}
	 * @see com.capgemini.simpleappblanche.services.ICustomerService#save(com.capgemini.simpleappblanche.dto.CustomerDto)
	 */
	@Override
	public CustomerDto save(final CustomerDto customerDto) {
		//transform DTO to BDD object
		final Customer customerTosave = mapperDozer.map(customerDto, Customer.class);
		final Customer customerReadyTosave = CustomerHelper.prepareCustomerToSave(customerTosave);
		
		//save
		final Customer customerUpdated =  customerDao.merge(customerReadyTosave);
		
		//transform BDD object to DTO 
		final CustomerDto result = mapperDozer.map(customerUpdated, CustomerDto.class);
		
		return result;
	}
	
}
